package socket_net_code.test;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Paths;

public class TCPServer {
    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(12345)) {
            System.out.println("Server started. Listening for connections...");

            Socket clientSocket = serverSocket.accept();
            System.out.println("Connection established.");

            try (
                    BufferedReader in = new BufferedReader(
                            new InputStreamReader(clientSocket.getInputStream()));
                    BufferedWriter writer = Files.newBufferedWriter(Paths.get("output.txt"))) {

                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    System.out.println("Received from client: " + inputLine);
                    writer.write(inputLine);
                    writer.newLine(); // Add a newline character
                }

                System.out.println("Data written to file.");
            } catch (IOException e) {
                System.err.println("Error writing to file: " + e.getMessage());
            }

            clientSocket.close();
        } catch (IOException e) {
            System.err.println("Error starting server: " + e.getMessage());
        }
    }
}
